import React, {Component, PureComponent} from 'react';
import {
    View, Text, FlatList,
    StyleSheet, Dimensions
} from 'react-native';

import ListItem from './ListItem'
import cleanTitle from '../utils/TitleCleaner';

const {width: screenWidth} = Dimensions.get('window');

export default class AlimamaList extends PureComponent {
    urlBase = `http://pub.alimama.com/items/search.json?perPageSize=20&q=女装`;
    state = {
        items: [],
        isRefreshing: false
    }
    currentPage = 0;
    isFetching = false;
    _renderItem = ({item}) => {
        const itemWrapper = {
            title: item.title,
            imgUrl: 'http:' + item.pictUrl,
        };
        return <ListItem style={styles.item} item={itemWrapper} itemWidth={screenWidth / 2 - 10}/>
    };
    _keyExtractor = (item, index) => item.auctionId.toString() + index;
    _getItemLayout = (data, index) => {
        return {
            length: 120,
            offset: Math.floor(index / 2) * 120,
            index,
        }
    };
    _fetchItems = async () => {
        let url = `${this.urlBase}&toPage=${this.currentPage}`
        console.log(`fetching page: ${this.currentPage}`);
        if (this.isFetching) {
            console.log('Fetching data in another request, return...');
            return;
        }
        this.isFetching = true;
        let data = await this._doFetch(url);
        if (data === null) {
            console.log('No data');
        }
        else {
            console.log(`Fetched ${data.length} items`);
            data = data.map(item => {
                item.title = cleanTitle(item.title);
                return item;
            })
            // let items = this.state.items.slice();
            this.setState({
                items:  this.state.items.concat(data),
            });
            this.currentPage += 1;
            this.isFetching = false;
        }
        this.setState({isRefreshing: false})
    };
    _doFetch = (url) => {
        return fetch(url).then(resp => resp.text()).then(textResp => {
            const json = JSON.parse(textResp);
            return json;
        }).then(jsonResp => jsonResp.data.pageList).catch(err => {
            console.log('Fetching data failed', err);
            return null;
        })
    };
    _onRefresh = () => {
        console.log('Begin refreshing....')
        this.setState({
            isRefreshing: true,
            items: [],
        }, () => {
            console.log('Updated state')
            this.currentPage = 0;
            this._fetchItems();
        });
    }

    componentWillMount () {
        this._fetchItems();
    };
    render() {
        return (
            <View>
                <Text>Hello, world</Text>
                <FlatList
                    contentContainerStyle={styles.list}
                    data={this.state.items}
                    renderItem={this._renderItem}
                    keyExtractor={this._keyExtractor}
                    onEndReached={this._fetchItems}
                    onEndReachedThreshold={0.3}
                    // numColumns={2}
                    // getItemLayout={this._getItemLayout}
                    removeClippedSubviews={true}
                    legacyImplementation={true}
                    refreshing={this.state.isRefreshing}
                    onRefresh={this._onRefresh}
                />
            </View>
        );
    }
}

const styles = StyleSheet.create({
    list: {
        // flex: 1,
        flexDirection: 'row',
        flexWrap: 'wrap',
    },
    item: {
        // flex: 0.3,
        width: screenWidth / 2 - 10,
        margin: 3,
    },
});